<template>
    <el-form ref="formRef" :model="formData" :rules="rules" label-width="100px" :disabled="false">
        <el-form-item label="活动标题" prop="activity_name">
            <el-input
                v-model="formData.activity_name"
                maxlength="15"
                class="custom-width"
                show-word-limit
                placeholder="请输入标题名称"
                :disabled="isViewDisabled"
                @input="e => (formData.activity_name = validSe(e))" />
        </el-form-item>
        <el-form-item label="所属分组" prop="group_id">
            <el-cascader
                ref="cascaderRef"
                v-model="formData.group_id"
                class="custom-width"
                :props="defaultProps"
                :options="groupOptions"
                :disabled="isViewDisabled"
                @change="orgChange" />
        </el-form-item>
        <el-form-item label="活动时间" prop="period_type">
            <el-tooltip :disabled="!isEditDisabled" content="进行中的活动不支持修改活动时间" placement="top">
                <el-radio-group
                    v-model="formData.period_type"
                    prop="period_type"
                    :disabled="isViewDisabled || isEditDisabled"
                    @change="handlePeriodChange">
                    <el-radio :label="1">永久有效</el-radio>
                    <el-radio :label="2">固定期限</el-radio>
                </el-radio-group>
            </el-tooltip>
            <el-tooltip :disabled="!isEditDisabled" content="进行中的活动不支持修改活动时间" placement="top">
                <el-form-item v-if="formData.period_type == 2">
                    <span>
                        <el-date-picker
                            v-model="formData.effect_date"
                            type="datetimerange"
                            :disabled-date="disabledDate"
                            format="YYYY-MM-DD HH:mm:ss"
                            :disabled="isViewDisabled || isEditDisabled"
                            value-format="YYYY-MM-DD HH:mm:ss"
                            :default-time="defaultTime()"
                            range-separator="-"
                            start-placeholder="开始时间"
                            end-placeholder="结束时间"
                            @change="validateField('period_type')" />
                    </span>
                </el-form-item>
            </el-tooltip>
        </el-form-item>
    </el-form>
</template>
<script lang="ts" setup>
import { getGroupList } from '@/api/concreation';
import { reactive, ref, defineExpose, onBeforeMount, computed } from 'vue';
import { FormInstance, FormRules } from 'element-plus';
import { useRoute } from 'vue-router';
import { defaultTime } from '@/utils/utils';
import { FormData } from '../interface';
import { useStore } from '@/store';

/* 默认分组 */
const store = useStore();
const route: any = useRoute();
store.dispatch('setGroupId', +route.query?.group_id || 0);

const routeType = computed(() => {
    // 跳转类型
    return route.query.type;
});
const isEditDisabled = computed(() => {
    // 编辑下禁用
    return routeType.value === 'edit' && activityStatus.value == 2;
});
const isViewDisabled = computed(() => {
    // 查看下禁用
    return routeType.value === 'view';
});

/* ================================表单内容================================ */
const formRef = ref<FormInstance>();
const cascaderRef: any = ref(null); // 选择分组ref
const formData = reactive<FormData>({
    official_account_id: '', //公众号id
    activity_name: '', // 活动标题
    group_id: +route.query?.group_id || 0, //分组id
    period_type: 2, // 活动有效期 2-固定 1-永久
    effect_date: ['', ''] //  有效期
});
const activityStatus: any = ref(); //活动状态 2结束
const disabledDate = (data: any) => {
    return +data < +new Date() - 86400000;
};
const periodValidator = (ruls: any, value: any, callback: any) => {
    if (!value) return callback(new Error('请选择活动有效期'));

    if (value === 2) {
        const result = formData?.effect_date?.every((item: any) => item);
        if (!result) return callback(new Error('请选择活动有效期'));
    }
    callback();
};
const rules = reactive<FormRules>({
    activity_name: [{ required: true, message: '请输入活动标题', trigger: 'blur' }],
    period_type: [{ required: true, validator: periodValidator, trigger: 'blur' }],
    group_id: [{ required: true, message: '请选择活动分组', trigger: 'change' }]
});
// 禁止输入特殊字符
const validSe = (value: any) => {
    value = value
        .replace(/[`~!@#$%^&*()_\-+=<>?:"{}|,./;'\\[\]·~！@#￥%……&*（）——\-+={}|《》？：“”【】、；‘’，。、]/g, '')
        .replace(/\s/g, '');
    return value;
};

const validateField = val => {
    formRef?.value?.validateField(val);
};
/* ================================表单内容================================ */

/* ================================分组================================ */
const groupOptions = reactive<Array<any>>([]);
const defaultProps = {
    checkStrictly: true, // 是否严格的遵守父子节点不互相关联
    emitPath: false,
    multiple: false,
    label: 'name',
    value: 'id'
};
// 获取活动分组
const onGroupgList = async () => {
    const res: any = await getGroupList({ type: 27, name: '' });
    groupOptions.push(...res.data);
};

onBeforeMount(() => {
    onGroupgList();
});
/* ================================分组================================ */

const handlePeriodChange = val => {
    if (val == 1) {
        formData.effect_date = ['', ''];
        validateField('period_type');
    }
};
// 下一步/获取表单的值
const getParams = async (isValid: boolean) => {
    const result = await formRef.value.validate();
    if (isValid) return result;
    if (result) {
        const extent_date =
            formData.period_type === 2
                ? {
                      end_date: formData.effect_date[1],
                      begin_date: formData.effect_date[0],
                      effect_date: undefined
                  }
                : {};
        return {
            ...formData,
            ...extent_date
        };
    }
};
const setDetailInfo = (detailInfo: any) => {
    const { activity_name, group_id, period_type, begin_date, end_date, status, official_account_id } = detailInfo;
    activityStatus.value = status;
    formData.activity_name = activity_name;
    formData.group_id = group_id;
    formData.official_account_id = official_account_id;
    formData.period_type = period_type;
    formData.effect_date = [begin_date || '', end_date || ''];
};
// 选择完地区后立即关闭
const orgChange = () => {
    cascaderRef.value.togglePopperVisible();
};
defineExpose({
    formData,
    getParams,
    setDetailInfo
});
</script>

<style lang="scss" scoped>
@import './scss/Form';
</style>
